import java.util.Scanner;

public class NGuessNumber {
    Scanner scan = new Scanner(System.in);
    int [] answer = new int[4];
    int [] guess = new int[4];

    public void generateAnswer() {
        int i = 0;
        while (i < 4) {
            int candidate = (int) (Math.random() * 10);
            boolean hasDuplicate = false;
            for (int j = 0; j < i; j++) {
                if (answer[j] == candidate) {
                    hasDuplicate = true;
                    break;
                }
            }
            if (hasDuplicate) {
                continue;
            } else {
                answer[i] = candidate;
                i = i + 1;
            }
        }
    }

    public void receiveGuess() {
        int i=0;
        while (i<4){
            try{
                guess[i]= scan.nextInt();
            }catch (Exception e){
                System.out.println("请输入0-9之间的4个数字!");
                scan.next();
                continue;
            }
            i =i + 1;
        }
    }

    public boolean hasDuplicateGuess() {
        for (int i = 0; i < 4; i++) {
            for (int j=i+1; j<4; j++){
                if (guess[i] == guess[j]){
                    System.out.println("有重复数字！请重新输入!");
                    return true;
                }
            }
        }
        return false;
    }

    public int getA(){
        int a=0;
        for (int i=0; i<4;i++){
            if (answer[i] ==guess[i]){
                a = a+1;
            }
        }
        return a;
    }

    public int getB(){
        int b=0;
        for (int i=0;i<4;i++){
            for (int j=0;j<4;j++){
                if (guess[j]==answer[i] && i !=j){
                    b=b+1;
                }
            }
        }
        return b;
    }

    public String playAgain(){
        return scan.next();
    }

    public void printNumbers(int t){
        int [] number = new int[4];
        if (t==0){
            number=answer;
        }else{
            number=guess;
        }
        for (int i=0; i<4;i++){
            System.out.println(number[i]);
        }
    }

    public static void main(String[] args) {
        NGuessNumber ngn = new NGuessNumber();
        String again;
        do {
            ngn.generateAnswer();
            int a,b;
            do {
                System.out.println("请输入0-9之间的不重复的数字: ");
                do {
                    ngn.receiveGuess();
                }while (ngn.hasDuplicateGuess());
                a= ngn.getA();
                b= ngn.getB();
                if (a !=4){
                    System.out.println(a+"A"+b+"B");
                }else{
                    System.out.println("恭喜你猜对啦！");
                }
            }while (a != 4);
            System.out.println("再玩一次吗？(y/n)");
            again = ngn.playAgain();
        }while (!again.equalsIgnoreCase("n"));

    }
}
